﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

namespace Assets
{
    internal class CubeBody:MonoBehaviour
    {
        private Transform lastBody;
        private Vector3 lastPos,startPos,stepPos;
        private Quaternion lastRotation,startRot;
        public Queue<Vector3> road;
        float dis = 0;
        float needTime,timer,stepTime;
        public static int roadPointCount = 10;
        public void Init(Transform lastBody)
        {
            this.lastBody = lastBody;
            lastPos = lastBody.position;
            startPos = transform.position;
            road = new Queue<Vector3>(roadPointCount);
            for (int i = 1; i <= roadPointCount; i++)
            {
                road.Enqueue(Vector3.Lerp(startPos,lastPos,i*1f/roadPointCount));
            }
            dis = Vector3.Distance(transform.position,lastPos);
            lastRotation = Quaternion.LookRotation(lastPos - startPos);
            startRot = transform.rotation;
            needTime = dis / 5f;
            stepTime = needTime / roadPointCount;
            stepPos=road.Dequeue();
        }
        public void MyUpdate()
        {
            timer += Time.deltaTime;

            if (timer <= stepTime)
            {
                transform.rotation = Quaternion.Lerp(startRot, lastRotation, timer / stepTime);
                transform.position = Vector3.Lerp(startPos, stepPos, timer / stepTime);
            }
            else
            {
                stepPos = road.Dequeue();
                road.Enqueue(lastBody.position);
                //lastPos = lastBody.position;
                startPos = transform.position;
                lastRotation = Quaternion.LookRotation(stepPos - startPos);
                //lastRotation = lastBody.rotation;
                //lastRotation = lastBody.rotation;
                startRot = transform.rotation;

                timer = 0;
            }
        }
    }
}
